package com.gitee.apecome.core.remote;

import com.gitee.apecome.core.remote.bean.ApeRpcRequest;
import com.gitee.apecome.core.remote.bean.ApeRpcResponse;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.NANOSECONDS;


public class ApeRpcFutureResponse {

    private ApeRpcRequest request;

    private ApeRpcResponse response;

    private ApeRpcFactory factory;

    private Object lock = new Object();

    private volatile Boolean isDone = Boolean.FALSE;

    public ApeRpcFutureResponse(ApeRpcFactory factory, ApeRpcRequest request) {
        this.factory = factory;
        this.request = request;

        setFutureRepsonse();
    }

    void removeFuture(String requestId) {
        factory.removeFuture(requestId);
    }

    void setFutureRepsonse() {
        factory.setFutureResponse(request.getRequestId(), this);
    }

    public void setResponse(ApeRpcResponse response) {
        synchronized (lock) {
            isDone = Boolean.TRUE;
            this.response = response;
            lock.notifyAll();
        }
    }

    public ApeRpcResponse get() {
        try {
            if (!isDone) { // 如果当前请求可以用（请求未完成）
                synchronized (lock) {
                    if (Objects.isNull(response)) {
                        lock.wait();
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return response;
    }
}
